﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Summary description for User
/// </summary>
public class UserModel : SQLAccess
{
	public UserModel()
	{
		
	}
    
    public DataTable testTable() {
        String sql = "SELECT [USER].* FROM [USER]";
        return executeQuery(sql);
    }

    public bool createNewUser(UserDTO dto) {
        if (connect()) { //if connect successful
            //call the createNewUser stored procedure
            _command = new System.Data.SqlClient.SqlCommand("createNewUser", _conn);
            _command.CommandType = CommandType.StoredProcedure;

            _command.Parameters.Add(new SqlParameter("@name", dto.TenUser));
            _command.Parameters.Add(new SqlParameter("@address", dto.DiaChi));
            _command.Parameters.Add(new SqlParameter("@phoneNumber", dto.DienThoai));
            _command.Parameters.Add(new SqlParameter("@login", dto.TenDangNhap));
            _command.Parameters.Add(new SqlParameter("@password", dto.MatKhau));
            _command.Parameters.Add(new SqlParameter("@typeID", dto.MaLoaiUser));
            SqlParameter pa = _command.Parameters.Add("@out", SqlDbType.Int);
            pa.Direction = ParameterDirection.Output;
            
            //execute store procedure
            _command.ExecuteNonQuery();
            //get the result
            int res = (int) pa.Value;
            disconnect();

            if (res == 1) // if add successful
                return true;
            else //add fail / the user was exist
                return false;
        }

        return false;
    }

    public bool checkLogin(UserDTO dto) {
        if (connect()) { //if connect successful
            //call the createNewUser stored procedure
            _command = new System.Data.SqlClient.SqlCommand("checkLogin", _conn);
            _command.CommandType = CommandType.StoredProcedure;

            _command.Parameters.Add(new SqlParameter("@login", dto.TenDangNhap));
            _command.Parameters.Add(new SqlParameter("@password", dto.MatKhau));            
            SqlParameter pa = _command.Parameters.Add("@result", SqlDbType.Int);
            pa.Direction = ParameterDirection.Output;

            //execute store procedure
            _command.ExecuteNonQuery();
            //get the result
            int res = (int)pa.Value;
            disconnect();

            if (res == 1) // valid user
                return true;
            else //invalid
                return false;
        }

        return false;
    }
}